package cn.tpshion.redismq.common;

import cn.dev33.satoken.exception.NotLoginException;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常捕获
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public R<Void> bindExceptionHandler(BindException e) {
        FieldError fieldError = e.getFieldErrors().get(0);
        log.error("BindException: errorMsg={}", fieldError.getDefaultMessage());
        return R.error(ResultCodeEnum.BAD_REQUEST, fieldError.getDefaultMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Void> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldErrors().get(0);
        log.error("MethodArgumentNotValidException: errorMsg={}", fieldError.getDefaultMessage());
        return R.error(ResultCodeEnum.BAD_REQUEST, fieldError.getDefaultMessage());
    }

    @ExceptionHandler({HttpMessageNotReadableException.class, ValidationException.class, ServletRequestBindingException.class})
    public R<Void> httpMessageNotReadableExceptionHandler(Exception e) {
        log.error("ServletRequestBindingException: errorMsg={}", e.getMessage());
        return R.error(ResultCodeEnum.BAD_REQUEST, e.getMessage());
    }

    /**
     * 业务异常处理
     */
    @ExceptionHandler(BizException.class)
    public R<Void> bizExceptionHandler(BizException e) {
        log.error("BizException: errorMsg={} {}", e.getMessage(), handleException(e));
        return R.error(ResultCodeEnum.BIZ_SERVER_ERROR, e.getMessage());
    }

    /**
     * 系统异常处理
     */
    @ExceptionHandler(Exception.class)
    public R<Void> exceptionHandler(Exception e) {
        log.error("SysException:{}", e.getMessage(), e);
        return R.error(ResultCodeEnum.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(NotLoginException.class)
    public R<Void> notLoginException(NotLoginException e) {
        log.error("NotLoginException: errorMsg={}", e.getMessage());
        return R.error(ResultCodeEnum.UNAUTHORIZED, e.getMessage());
    }

    private String handleException(Exception e) {
        StackTraceElement[] stackTrace = e.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if (stackTraceElement.getClassName().contains("AssertUtil")) {
                return stackTrace[1].toString();
            }
        }
        return e.toString();
    }
}

